<template>
  <div class="app-container">

    <el-form :model="queryParams" :rules="rules" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item style="margin-left: -20px" label="乘客姓名" prop="passengerName">
        <el-select
          v-model="queryParams.passengerName"
          filterable
          @change="handleChange"
        >
          <el-option
            v-for="item in ckXmOptions"
            :key="item.ckName"
            :label="item.ckName"
            :value="item.ckName"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: -10px" label="乘客证件号" prop="passengerIdCard">
        <el-select
          v-model="queryParams.passengerIdCard"
          filterable
        >
          <el-option
            v-for="item in ckIdCardOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: -25px" label="登机类型" prop="djLx">
        <el-select v-model="queryParams.djLx" clearable style="width: 120px" @change="changeDjLx">
          <el-option
            v-for="dict in dict.type.dj_lx"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-if="show && this.ckInfo != null" v-loading="loading" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="登机" name="first">
        <boarding :show="show && firstShow" :ck-info="ckInfo" :dj-lx="queryParams.djLx"
                  :zd-unload-status="ckInfo.zdUnloadStatus"
                  @zd-boarding-successful="zdBoardingSuccessful"
                  @zz-boarding-successful="zzBoardingSuccessful"></boarding>
      </el-tab-pane>
      <!--   直达航班   -->
      <el-tab-pane v-if="this.queryParams.djLx == '0'" label="称重-安检" name="second">
        <security-check :show="show && secondShow" :cxXlCzAjInfo="cxXlCzAjInfo"
                        :query-params="queryParams"
                        :boarding-status="ckInfo.boardingStatus"
                        @start-cz-aj-success="startCzAjSuccess"
        ></security-check>
      </el-tab-pane>
      <!--   直达航班   -->
      <el-tab-pane v-if="this.queryParams.djLx == '0'" label="值机" name="third">
        <zdzj :show="show && thirdShow" :print-status="printStatus"
              :ckxl-id="ckInfo.ckxlId" :start-zj="ckInfo.startZj"
              :dj-lx="this.queryParams.djLx" @startZjInterval="startZjInterval"
              @start-zd-zj-success="startZdZjSuccess"></zdzj>
      </el-tab-pane>
      <!--   中转航班   -->
      <el-tab-pane v-if="this.queryParams.djLx == '1'" label="中转值机" name="four">
        <zzzj :show="show && fourShow" :boarding-status="ckInfo.boardingStatus"
              :zzty-jl-jc = "zztyJlJc" :ckxl-id="ckInfo.ckxlId"
              :start-zz="ckInfo.startZz" :dj-lx="this.queryParams.djLx"
              @start-zz-zj-success="startZzZjSuccess"></zzzj>
      </el-tab-pane>
    </el-tabs>

    <el-empty v-if="this.queryParams.djLx == '1' && this.ckInfo == null"
              description="未查询到当前乘客的中转航班"></el-empty>

    <el-empty v-if="this.queryParams.djLx == '0' && this.ckInfo == null"
              description="未查询到当前乘客的值机航班"></el-empty>

  </div>
</template>

<script>

import { selectCkInfoByNickNameAndIdCard, getCkXmInfo, getCkIdCardByCkXm } from "@/api/ckxl/ck";
import { getCkxlCzAjInfo, getCkXlPrintInfo, getCkXlZztyJlJc} from "@/api/ckxl/xl";
import boarding from './boarding'
import securityCheck from './securityCheck'
import zdzj from './zdzj'
import zzzj from './zzzj'

export default {
  name: "Check",
  dicts: ['dj_lx'],
  components: { boarding, securityCheck, zdzj, zzzj },
  data() {
    return {
      activeName: 'first',
      // 查询参数
      queryParams: {
        passengerName: '',
        passengerIdCard: '',
        djLx:'0',
      },
      show:false,
      firstShow:false,
      secondShow:false,
      thirdShow:false,
      fourShow:false,
      // 表单校验
      rules: {
        passengerName: [
          { required: true, message: "乘客姓名不能为空", trigger: "blur" }
        ],
        passengerIdCard: [
          { required: true, message: "乘客证件号不能为空", trigger: "change" }
        ],
        djLx: [
          { required: true, message: "登机类型不能为空", trigger: "change" }
        ],
      },
      //乘客信息
      ckInfo:{},
      //乘客行李称重安检信息
      cxXlCzAjInfo:{},
      //条码打印状态
      printStatus:'0',
      //中转值机进料监测状态
      zztyJlJc:'0',
      loading: false,
      ckXmOptions: [{
        label:"",
        value:""
      }],
      ckIdCardOptions: [],
      timerId:null,
    };
  },
  /*watch: {
    'queryParams.passengerIdCard'(newVal, oldVal) {
      console.log(newVal)
      if (newVal.length > 6) {
        this.search = newVal.slice(0, 6); // 截取前6个字符并更新到search上
      }
    }
  },*/
  watch: {
    '$store.state.user.peopleNum': {
      handler:function(newVal,oldVal){
        if(newVal != oldVal){
          this.queryParams.passengerName = '';
          this.queryParams.passengerIdCard = '';
          this.getCkBaseInfo();
        }
      }
    },

    'printStatus': function(val)  {
      if(val == '1' && this.timerId){
        clearInterval(this.timerId);
      }
    },

    'ckInfo.startZj': function(val)  {
        if(val == '1' && this.printStatus == '1' && this.timerId){
          clearInterval(this.timerId);
        }
    },

    'zztyJlJc': function(val)  {
      if(val == '1' && this.timerId){
        clearInterval(this.timerId);
      }
    },

    'ckInfo.startZz': function(val)  {
      if(val == '1' && this.zztyJlJc == '1' && this.timerId){
        clearInterval(this.timerId);
      }
    },

  },
  created() {
  },
  mounted() {
    this.queryParams.passengerName = '';
    this.queryParams.passengerIdCard = '';
    this.getCkBaseInfo();
  },
  computed:{
  },
  methods: {

    //点击tab页
    handleClick(tab, event) {
      if(tab.index == 0 && tab.paneName == 'first'){
        clearInterval(this.timerId);
        this.handleQueryFirst();
      }
      if(tab.index == 1 && tab.paneName == 'second'){
        clearInterval(this.timerId);
        this.handleQuerySecond();
      }
      if(tab.index == 2 && tab.paneName == 'third'){
        //值机
        if(this.ckInfo.startZj == '0' && this.printStatus == '0'){
          this.startZjInterval();
        }else {
          this.handleQueryThird();
        }
      }
      if(tab.index == 1 && tab.paneName == 'four'){
        //中转
        if(this.ckInfo.startZz == '0' && this.zztyJlJc == '0'){
          this.startZzInterval();
        }else {
          this.handleQueryFour();
        }
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.show = false
      if(this.timerId){
        clearInterval(this.timerId);
      }
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          this.loading = true;
          this.getAllInfo();
          this.activeName = 'first';
          this.loading = false;
        }
      });
    },

    /** 搜索按钮操作 */
    handleQueryFirst() {
      this.firstShow = false;
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          this.getAllInfo();
          this.activeName = 'first';
        }
      });
    },

    /** 搜索按钮操作 */
    handleQuerySecond() {
      this.secondShow = false;
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          this.getAllInfo();
          this.activeName = 'second';
        }
      });
    },

    /** 搜索按钮操作 */
    handleQueryThird() {
      this.thirdShow = false;
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          this.getAllInfo();
          this.activeName = 'third';
        }
      });
    },

    /** 搜索按钮操作 */
    handleQueryFour() {
      //console.log("中转值机定时任务执行：执行");
      this.fourShow = false;
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          this.getAllInfo();
          this.activeName = 'four';
        }
      });
    },

    /** 直达登机成功 */
    zdBoardingSuccessful(msg) {
      this.show = false
      this.$modal.msgSuccess(msg);
      this.getAllInfo();
      this.activeName = 'second';
    },

    /** 中转登机成功 */
    zzBoardingSuccessful(msg) {
      this.show = false
      this.$modal.msgSuccess(msg);
      this.getAllInfo();
      this.activeName = 'four';
    },

    /** 启动称重-安检成功 */
    startCzAjSuccess(msg) {
      this.show = false
      this.$modal.msgSuccess(msg);
      this.getAllInfo();
      this.activeName = 'third';
    },

    /** 启动值机成功 */
    startZdZjSuccess(msg){
      this.show = false
      this.$modal.msgSuccess(msg);
      this.startZjInterval();
    },

    /** 启动中转值机成功 */
    startZzZjSuccess(msg){
      this.show = false
      this.$modal.msgSuccess(msg);
      this.startZzInterval();
    },

    //查询所有信息
    getAllInfo(){
      this.getCkInfo();
      if(this.queryParams.djLx == '0'){
        // 乘客称重-安检信息
        this.getCkCzAjInfo();
        // 乘客条码打印信息
        this.getCkPrintInfo();
      }else {
        //获取中转值机进料检测信息
        this.getZzzjJlJcInfo();
      }
    },

    /** 查询乘客信息 */
    getCkInfo() {
      this.fillCkIdCard();
      selectCkInfoByNickNameAndIdCard(this.queryParams).then(response => {
        if (response.data != null) {
          this.ckInfo = response.data
          this.show = true;
          this.firstShow = true;
          this.secondShow = true;
          this.thirdShow = true;
          this.fourShow = true;
        }else {
          this.ckInfo = null
        }
      });
    },

    // 获取真正的乘客证件号
    fillCkIdCard(){
      this.ckIdCardOptions.forEach(item => {
        if(item.label == this.queryParams.passengerIdCard){
          this.queryParams.passengerIdCard = item.value;
        }
      })
    },

    /** 查询乘客行李称重-安检信息 */
    getCkCzAjInfo() {
      getCkxlCzAjInfo(this.queryParams).then(response => {
        if(response.data != null){
          this.cxXlCzAjInfo = response.data;
        }else {
          this.cxXlCzAjInfo = null
        }
      });
    },

    /** 查询条码打印信息 */
    getCkPrintInfo() {
      getCkXlPrintInfo(this.queryParams).then(response => {
        if(response.msg != null){
          this.printStatus = response.msg;
        }else {
          //默认未打印
          this.printStatus = '0';
        }
      });
    },

    //获取中转值机进料检测信息
    getZzzjJlJcInfo(){
      getCkXlZztyJlJc(this.queryParams).then(response => {
        if(response.msg != null){
          this.zztyJlJc = response.msg;
        }else {
          //默认检测到进料
          this.zztyJlJc = '0';
        }
      });
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryIsTransfer = '';
      this.show = false;
      this.ckXmOptions = [];
      this.ckIdCardOptions = [];
    },

    /** 登机类型改变 */
    changeDjLx() {
      this.handleQuery();
    },

    // 防抖处理（500ms内仅触发一次）
    getCkBaseInfo() {
      getCkXmInfo().then(response => {
        if (response.data != null) {
          this.ckXmOptions = response.data
        }
      }).catch(() => {
        this.ckXmOptions = [];
      });
    },

    //选中乘客姓名
    handleChange(value){
      this.getCkIdCard(value);
    },

    //根据乘客姓名查询乘客身份证id
    getCkIdCard(ckName){
      getCkIdCardByCkXm(ckName).then(response => {
        this.ckIdCardOptions = [];
        if (response.data != null) {
          response.data.forEach(item => {
              this.ckIdCardOptions.push({
                'label': this.formatIdCard(item.idCard),
                'value': item.idCard
              })
            }
          )
          this.queryParams.passengerIdCard = this.ckIdCardOptions[0].label;
        }
      }).catch(() => {
        this.ckIdCardOptions = [];
      });
    },

    // 格式化显示身份证号（如：410*****123456）
    formatIdCard(idCard) {
      if(idCard != null){
        return idCard.replace(/(\d{4})\d+(\d{6})/, '$1*****$2');
      }
    },

    // 选中后的回调
    /*handleSelect(value) {
      console.log('选中:', value);
    },*/

    // 值机定时刷新，每隔3秒刷新一次
    startZjInterval() {
      this.timerId = setInterval(() => {
        this.handleQueryThird();
      }, 3000); // 每3000毫秒执行一次
    },

    // 中转值机定时刷新，每隔3秒刷新一次
    startZzInterval() {
      this.timerId = setInterval(() => {
        this.handleQueryFour();
      }, 3000); // 每3000毫秒执行一次
    },

  }
};
</script>

<style lang="scss" scoped>

</style>
